﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using eShop.Business;
using System.IO;
using System.Text.RegularExpressions;
using eShop.Model;

public partial class confirm_order : SitePublicBasePage
{
    private Int32 _OrderId
    {
        get
        {
            try
            {
                if (HttpContext.Current.Request.QueryString != null && !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["id"]))
                {
                    return Convert.ToInt32(HttpContext.Current.Request.QueryString["id"]);
                }
                else
                {
                    return -1;
                }
            }
            catch
            {
                return -1;
            }
        }
    }

    private string _Status
    {
        get
        {
            try
            {
                if (HttpContext.Current.Request.QueryString != null && !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["tran_status"]))
                {
                    return Imgalib.Utility.Cryptography.DecryptStringAES(HttpContext.Current.Request.QueryString["tran_status"]);
                }
                else
                {
                    return string.Empty;
                }
            }
            catch
            {
                return string.Empty;
            }
        }
    }

    private string _Transection_Id
    {
        get
        {
            return ViewState["_Transection_Id"].ToString();
        }
        set
        {
            ViewState["_Transection_Id"] = value;
        }
    }

    private string _Validation_Id
    {
        get
        {
            return ViewState["_Validation_Id"].ToString();
        }
        set
        {
            ViewState["_Validation_Id"] = value;
        }
    }

    private string _OrderStatus_Message
    {
        get
        {
            return ViewState["_OrderStatus_Message"].ToString();
        }
        set
        {
            ViewState["_OrderStatus_Message"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (!string.IsNullOrEmpty(_Status) && _OrderId != -1)
            {
                pnlbKash.Visible = false;
                btnConfirm.CausesValidation = false;
                btnConfirm.Attributes.Remove("ValidationGroup");
                StreamReader reader = new StreamReader(Page.Request.InputStream);
                String data = reader.ReadToEnd();
                reader.Close();

                string urlDecodedData = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(data));
                if (!string.IsNullOrEmpty(urlDecodedData))
                {
                    _OrderStatus_Message = urlDecodedData;
                
                }

                if (_Status == "success")
                {
                    uccResponseMessage.SetSuccessMessage(Server.HtmlDecode(@"Payment recevied, Thanks.Now click 'Proceed' button and complete the purchase."));
                    _Validation_Id = Regex.Matches(urlDecodedData, @"&val_id=.*?&")[0].Value.Replace("&val_id=", "").Replace("&", "");
                    _Transection_Id = Regex.Matches(urlDecodedData, @"tran_id=.*?&")[0].Value.Replace("tran_id=", "").Replace("&", "");
                }
                else
                {
                    uccResponseMessage.SetFailMessage(Server.HtmlDecode(@"Sorry failed to process payment.Now click 'Proceed' button and complete the purchase."));
                }
                
            }
            else
            {
                uccResponseMessage.SetNoticeMessage(Server.HtmlDecode(@"To pay easily from your mobile phone through bKash, click <a href='http://www.bkash.com/Register.php'>here</a> and get registered with bKash.If you are already a registered bKash user, make payment to following wallet no. " + ApplicationSettings._bKash_WALLET_NUMBER + " from your mobile phone. After making payment, insert your transaction id and your bKash mobile number in the respective fields. Now click 'Confirm & Complete Checkout' button and complete the purchase."));                
                pnlbKash.Visible = true;
                LoadData();
            }
        }

    }

    private void LoadData()
    {
        Order order = OrderManager.GetOrderById(SessionManager.OrderID);
        if (order != null)
        {
            litAmount.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(order.TotalAmount);
            litWalletNumber.Text = ApplicationSettings._bKash_WALLET_NUMBER;
        }
        else
        {
            uccResponseMessage.SetFailMessage("No order with order# " + SessionManager.OrderID + "found");
        }
    }
    protected void btnConfirm_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(_Status) && _OrderId != -1)
        {
            Order order = OrderManager.GetOrderById(SessionManager.OrderID);
            
            if (_Status == "success")
            {
                order.OrderStatus = OrderStatusType.CCSuccess;
                order.PaymentStatus = _OrderStatus_Message;
            }
            else
            {
                order.OrderStatus = OrderStatusType.CCFail;
            }

            OrderManager.UpdateOrder(order);
            try
            {
                new Email().SendInvoiceEmail(order, SessionManager.LoggedUser.Id);
            }
            catch
            {
            }
            finally
            {
                HttpContext.Current.Response.Redirect(CustomSiteMap.Receipt);
            }
        }
        else
        {
            Order order = OrderManager.GetOrderById(SessionManager.OrderID);
            order.OrderStatus = OrderStatusType.ManualAuthorization;
            order.PaymentStatus = txtBKashNumber.Text.Trim();
            order.TransectionId = txttransactionId.Text.Trim();
            OrderManager.UpdateOrder(order);
            try
            {
                new Email().SendInvoiceEmail(order, SessionManager.LoggedUser.Id);
            }
            catch
            {
            }
            finally
            {
                HttpContext.Current.Response.Redirect(CustomSiteMap.Receipt);
            }
        }
    }
}